<template>
  <basic-container>
    <avue-crud :option="option" :data="data" :page.sync="page" ref='crud' @current-row-change="handleCurrentRowChange" @row-save="rowSave" @row-del="rowDel" v-model="form" :permission="permissionList" @row-update="rowUpdate" :before-open="beforeOpen" @search-change="searchChange" @search-reset="searchReset" @selection-change="selectionChange" @current-change="currentChange" @size-change="sizeChange" @refresh-change="refreshChange" @on-load="onLoad">
      <template slot="menuRight">
        <table-right :crud='$refs.crud' :data='data' :addPermission="permission.publicproduct_match_add" :exportPermission='permission.publicproduct_match_export' :handleDelete="handleDelete" :delPermission="permission.publicproduct_match_delete" :refreshChange='refreshChange'>
        </table-right>
      </template>
      <template slot-scope="{scope,row}" slot="menuForm">
        <el-button icon="el-icon-circle-plus" v-if="type=='add'" v-loading="goon" size="mini" plain type="primary" @click.stop="saveAndGoon()">保存并继续</el-button>
      </template>
      <template slot-scope="{row}" slot="menu">
        <el-tooltip class="item" effect="dark" content="查看" placement="bottom">
          <el-button icon="el-icon-view" size="small" type="text" @click.stop="$refs.crud.rowView(row,row.$index)" v-if="permission.publicproduct_match_view"></el-button>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="编辑" placement="bottom">
          <el-button icon="el-icon-edit" size="small" type="text" @click.stop="$refs.crud.rowEdit(row,row.$index)" v-if="permission.publicproduct_match_edit"></el-button>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="删除" placement="bottom">
          <el-button icon="el-icon-delete" size="small" type="text" @click.stop="rowDel(row)" v-if="permission.publicproduct_match_delete&&row.dataSource=='2'"></el-button>
        </el-tooltip>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
import { getUnitList } from '@/api/basic/unit';
import { codesReg } from '@/util/zhengze';
import { searchProduct } from '@/api/project/information/baseinfor';

import { getMatchList, addMatch, removeMatch, updateMatch, getMatch } from '@/api/project/productData/product';
import { getMaterialgroupList } from '@/api/project/productData/baseData';
import { mapGetters, mapState } from 'vuex';
import { init } from '@/mixins/init';
import { searchSpan, culomnSpan } from '@/api/span';

export default {
  mixins: [init],
  data() {
    return {
      loadings: false,
      option: {
        highlightCurrentRow: true,
        dialogWidth: '1000',
        labelWidth: 120,
        searchGutter: 0,
        menuWidth: 100,
        tip: false,
        border: true,
        index: true,
        viewBtn: false,
        editBtn: false,
        addBtn: false,
        delBtn: false,
        selection: true,
        searchMenuSpan: searchSpan(3),
        column: [
          {
            label: '客户名称',
            prop: 'customerNo',
            filterable: true,
            searchFilterable: true,
            type: 'select',
            dicUrl: '/api/customerlinkman/selectCustomer',
            props: {
              label: 'customerName',
              value: 'id',
            },
            // slot: true,
            search: true,
            disabled: false,
            searchSpan: culomnSpan(),
            rules: [
              {
                required: true,
                message: '请选择客户',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '产品图号',
            prop: 'customerProductDrawingNo',
            search: true,
            searchSpan: culomnSpan(),
            rules: [
              {
                required: true,
                message: '请输入产品图号',
                trigger: 'blur',
              },
            ],
          },
          // {
          //   label: '客户产品编码',
          //   prop: 'customerProductNo',
          //   rules: [
          //     {
          //       required: true,
          //       message: '请输入客户产品编码',
          //       trigger: 'blur',
          //     },
          //   ],
          // },
          {
            label: '客户产品名称',
            prop: 'customerProductName',
            rules: [
              {
                required: true,
                message: '请输入产品名称',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '项目名称',
            prop: 'projectId',
            type: 'select',
            disabled: false,
            filterable: true,
            dicUrl: '/api/projectinfo/list',
            props: {
              label: 'projectName',
              value: 'id',
            },
          },
          {
            label: '产品编码',
            prop: 'internalProductId',
            slot: true,
            hide: true,
            disabled: false,
            showColumn: false,
            filterable: true,
            type: 'select',
            dicData: [],
            props: {
              label: 'label',
              value: 'id',
            },
            span: 12,
            minWidth: 150,
            rules: [
              {
                required: true,
                message: '请选择内部产品编码',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '内部图号',
            prop: 'innerDrawingNo',
            type: 'select',
            disabled: false,
            addDisplay: false,
          },
          {
            label: '产品编码',
            prop: 'innerProductNo',
            display: false,
          },
          {
            label: '产品名称',
            prop: 'innerProductName',
            search: true,
            disabled: false,
            searchSpan: culomnSpan(),
            addDisplay: false,
          },
          {
            label: '数据来源',
            prop: 'dataSource',
            type: 'select',
            disabled: false,
            addDisplay: false,
            dicData: [
              { label: '项目', value: '1' },
              { label: '新建', value: '2' },
            ],
          },
          {
            label: '在售状态',
            prop: 'status',
            type: 'switch',
            value: 1,
            activeColor: 'green',
            inactiveColor: 'red',
            dicData: [
              {
                label: '停售',
                value: 2,
              },
              {
                label: '在售',
                value: 1,
              },
            ],
          }
        ],
      },
    };
  },
  computed: {
    ...mapGetters(['permission']), //权限映射
    permissionList() {
      //按钮权限设置
      return {
        addBtn: this.vaildData(this.permission.publicproduct_match_add, false),
        viewBtn: this.vaildData(this.permission.publicproduct_match_view, false),
        delBtn: this.vaildData(this.permission.publicproduct_match_delete, false),
        editBtn: this.vaildData(this.permission.publicproduct_match_edit, false),
      };
    },
  },
  watch: {},
  methods: {
    rowSave(row, done, loading) {
      row.dataSource = '2';
      addMatch(row).then(
        () => {
          if (this.goon) {
            loading();
            for (let key in this.$refs.crud.value) {
              this.$refs.crud.value[key] = null;
            }
            this.goon = false;
            this.onLoad(this.page);
          } else {
            this.onLoad(this.page);
            done();
          }
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        },
        (error) => {
          this.goon = false;
          window.console.log(error);
          loading();
        }
      );
    },
    // rowSave(row, done, loading) {
    //   row.dataSource = '2';
    //   addMatch(row).then(
    //     () => {
    //       this.onLoad(this.page);
    //       this.$message({
    //         type: 'success',
    //         message: '操作成功!',
    //       });
    //       done();
    //     },
    //     (error) => {
    //       window.console.log(error);
    //       loading();
    //     }
    //   );
    // },
    rowUpdate(row, index, done, loading) {
      updateMatch(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          done();
        },
        (error) => {
          window.console.log(error);
          loading();
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return removeMatch(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      let isFromProject = false;
      isFromProject = this.selectionList.some((item) => {
        return item.dataSource != '2';
      });
      if (isFromProject) {
        this.$message.warning('来源于项目的数据不可删除');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return removeMatch(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      this.type = type;
      if (this.form.dataSource==1) {
        this.$set(this.option.column[0], 'disabled', true)
        this.$set(this.option.column[3], 'disabled', true)
        this.$set(this.option.column[4], 'disabled', true)
        this.$set(this.option.column[5], 'disabled', true)
        this.$set(this.option.column[7], 'disabled', true)
        this.$set(this.option.column[8], 'disabled', true)
      } else {
        this.$set(this.option.column[0], 'disabled', false)
        this.$set(this.option.column[3], 'disabled', false)
        this.$set(this.option.column[4], 'disabled', false)
        this.$set(this.option.column[5], 'disabled', false)
        this.$set(this.option.column[7], 'disabled', false)
        this.$set(this.option.column[8], 'disabled', false)
      }
      if (['edit', 'view'].includes(type)) {
        getMatch(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchChange(params, done) {
      //搜索触发
      this.query = params;
      // this.query.innerDrawingNo = this.query.customerProductDrawingNo;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    onLoad(page, params = this.query) {
      //加载table
      getMatchList(page.currentPage, page.pageSize, params).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
      });
      searchProduct().then((res) => {
        const data = res.data.data;
        const column = this.findObject(this.option.column, 'internalProductId');
        column.dicData = res.data.data.map((item) => {
          item.label = item.materialName + '(' + item.materialNo + ')';
          return item;
        });
      });
      // getUnitList().then((res) => {
      //   let data = res.data.data;
      //   const column = this.findObject(this.option.column, 'unit');
      //   column.dicData = data.map((item) => {
      //     return {
      //       label: item.name + '(' + item.code + ')',
      //       value: item.code,
      //     };
      //   });
      // });
    },
  },
  created() {},
};
</script>

<style>
.avue-crud__pagination {
  margin-top: 0;
  padding: 0;
}
</style>
